<template>
  <el-dialog v-model="visible" title="修改" :close-on-click-modal=false :destroy-on-close=true>
    <el-form :model="UserForm" label-width="80px" ref="UserAddRef" :rules="rules">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="UserForm.name" disabled/>
      </el-form-item>
      <el-form-item label="姓名" prop="alias">
        <el-input v-model="UserForm.alias" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="UserForm.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="UserForm.phone" />
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="save">保存</el-button>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import apiUser from '@/api/system/user'
import {ElNotification} from 'element-plus'

const visible = ref(false)
const props = defineProps({modelValue: Boolean, userData: Object})
const emit = defineEmits(['update:modelValue', 'success'])

const UserAddRef = ref()
const UserForm = ref({
  id: '',
  name: '',
  alias: '',
  email: '',
  phone: '',
  extra: {}
})

watch(() => props.modelValue, (val) => {
  visible.value = val
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

watch(() => props.userData, (newVal) => {
  if (newVal) {
    Object.assign(UserForm.value, newVal)
  }
}, { immediate: true, deep: true })

const save = async () => {
    try {
      const valid = await UserAddRef.value.validate()
      if (!valid) return
      const resp = apiUser.updateUser(UserForm.value)
      visible.value = false
      UserAddRef.value.resetFields()

      ElNotification({message: "修改成功", type: 'success'})
      emit('success')
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}


const rules = {
  name: [{"required": true, "message": "请输入姓名", "trigger": "blur"}]
}
</script>

<style>
</style>
